package master

import (
	"crontab/common"
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"time"
)

var (
	G_apiServer *ApiServer
)

type ApiServer struct {
	httpServer *http.Server
}

// 获取worker节点列表
func WorkerListHand(w http.ResponseWriter, r *http.Request) {
	var (
		workerList []*common.Worker
		err error
	)
	workerList,err = G_WorkerMgr.GetWorkerList()
	if err != nil {
		w.Write(common.BuildResponse(500,err.Error(),workerList))
		return
	}
	w.Write(common.BuildResponse(0,"获取worker列表成功",workerList))
	return

}

// 获取日志列表
func JobLogHand(w http.ResponseWriter, r *http.Request) {
	var (
		err error
		jobName string
		skipParam string
		limitParam string
		skip int
		limit int
		jobList []*common.JobLog
	)
	if err = r.ParseForm();err != nil {
		w.Write(common.BuildResponse(400,"解析错误,参数传递不正确",nil))
		return
	}

	jobName = r.Form.Get("name")
	skipParam = r.Form.Get("skip")
	limitParam = r.Form.Get("limit")

	if skip,err = strconv.Atoi(skipParam);err != nil {
		skip = 0
	}
	if limit,err = strconv.Atoi(limitParam);err != nil {
		limit = 20
	}

	if jobList,err = G_LogMgr.ListLog(jobName,skip,limit); err != nil {
		w.Write(common.BuildResponse(500,err.Error(),jobList))
		return
	}
	w.Write(common.BuildResponse(0,"获取列表成功",jobList))
	return


}

// name =
func JobKillHand(w http.ResponseWriter, r *http.Request) {
	// 解析参数
	var (
		err error
		jobName string
	)
	if err = r.ParseForm(); err != nil {
		w.Write(common.BuildResponse(400,"解析参数错误",nil))
		return
	}
	jobName = r.PostForm.Get("name")
	// 调用etcd写入杀死任务信号
	err = G_EtcdJob.EtcdKillJob(jobName)
	if err != nil {
		w.Write(common.BuildResponse(500,"写入杀死命令信号失败",nil))
		return
	}
	w.Write(common.BuildResponse(0,"写入杀死命令信号成功",nil))
	return
}

func JobListHand(w http.ResponseWriter,r *http.Request) {
	var (
		jobList []*common.Job
		err error
	)
	// 查询所有的etcd下的数据
	jobList,err =  G_EtcdJob.EtcdJobList()
	if err != nil {
		w.Write(common.BuildResponse(500,"获取任务列表失败",nil))
		return
	}
	w.Write(common.BuildResponse(0,"获取任务列表成功",jobList))
	return
}

// name =
func JobDelHand(w http.ResponseWriter,r *http.Request) {
	var (
		err error
		jobName string
		jobObj *common.Job
	)
	// 解析参数
	if err = r.ParseForm(); err != nil {
		w.Write(common.BuildResponse(400,"传递参数不正确",nil))
		return
	}
	jobName = r.PostForm.Get("name")

	if jobName == "" {
		w.Write(common.BuildResponse(400,"name参数不能为空",jobObj))
		return
	}

	// 删除job
	jobObj,err = G_EtcdJob.DelEtcdJob(jobName)
	if err != nil {
		w.Write(common.BuildResponse(500,"删除etcd Job任务失败",jobObj))
		return
	}

	w.Write(common.BuildResponse(0,"删除etcd Job任务成功",jobObj))

}

// 任务信息保存
// job = {"jobName","","command","","exp",""}
func JobSaveHand(w http.ResponseWriter, r *http.Request) {
	var (
		err error
		paramsJob string
		job *common.Job
		oldJob *common.Job
	)
	if err = r.ParseForm();err != nil {
		log.Printf("解析传入参数失败")
		w.Write(common.BuildResponse(500,"解析参数错误",nil))
		return
	}
	paramsJob = r.PostForm.Get("job")
	log.Printf("job参数为: " + paramsJob)
	job = &common.Job{}
	err = json.Unmarshal([]byte(paramsJob),job)
	if err != nil {
		w.Write(common.BuildResponse(400,"传入参数格式不正确",nil))
		return
	}

	// 保存job
	oldJob,err = G_EtcdJob.SaveJob(job)
	if err != nil {
		w.Write(common.BuildResponse(500,err.Error(),oldJob))
		return
	}
	w.Write(common.BuildResponse(0,"",oldJob))
	return

}

// 初始化http服务
func InitHttpServer()(err error) {
	var (
		mux *http.ServeMux
		httpServer *http.Server
		webDir http.Dir
		webHand http.Handler
	)
	// 生成路由
	mux = http.NewServeMux()
	//路由对应
	// 保存任务
	mux.HandleFunc("/job/save",JobSaveHand)
	// 删除任务
	mux.HandleFunc("/job/delete",JobDelHand)
	// 任务列表
	mux.HandleFunc("/job/list",JobListHand)
	// 杀死任务
	mux.HandleFunc("/job/kill",JobKillHand)
	// 日志列表
	mux.HandleFunc("/job/log",JobLogHand)
	// worker节点列表
	mux.HandleFunc("/worker/list",WorkerListHand)

	// 加载html
	webDir = http.Dir(G_Config.WebRootDir)
	webHand = http.FileServer(webDir)
	mux.Handle("/",http.StripPrefix("/",webHand))

	// 配置http服务配置
	httpServer = &http.Server{
		Addr: ":" + strconv.Itoa(G_Config.ApiPort),
		ReadTimeout: time.Second * time.Duration(G_Config.ApiReadTimeout),
		WriteTimeout: time.Second * time.Duration(G_Config.ApiWriteTimeout),
		Handler: mux,
	}

	G_apiServer = &ApiServer{
		httpServer: httpServer,
	}
	// 启动服务端
	go httpServer.ListenAndServe()
	return nil

}